package es.cazadoresmadridejos.beans.controller.reason;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import es.cazadoresmadridejos.beans.manager.reason.ReasonManager;
import es.cazadoresmadridejos.beans.validator.reason.ReasonValidator;
import es.cazadoresmadridejos.model.Reason;
import es.cazadoresmadridejos.propertyeditor.ReasonPropertyEditor;
import es.cazadoresmadridejos.util.validation.ValidationContainer;


@Controller
public class ReasonCreateModifyController {

	@Autowired private ReasonManager reasonManager;
	@Autowired private ReasonValidator reasonValidator;
	@Autowired private MessageSource messageSource;
	
	@InitBinder
	public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Throwable{
		binder.registerCustomEditor(Reason.class, new ReasonPropertyEditor(reasonManager));
	}
	
	@RequestMapping(value="/reasonCreateModify.html",method=RequestMethod.GET)
	public ModelAndView createModify(
			@RequestParam(value="id",required=false) Reason reason) throws Throwable {
		ModelAndView mv = new ModelAndView();
		if(reason == null){
			reason = new Reason();
			mv.addObject("type","create");
		}else{
			mv.addObject("type","update");
		}
		mv.addObject("reason",reason);
		
		return mv;
	}
	@RequestMapping(value="/reasonCreateModify.html",method=RequestMethod.POST)
	public ModelAndView submit(
			@ModelAttribute("reason") Reason reason, 
			BindingResult result, 
			SessionStatus status,
			HttpServletRequest request
			) throws Throwable {
		
		ModelAndView mv = new ModelAndView("redirect:index.html");
		List<ValidationContainer> errors = reasonValidator.validate(reason);
		if(errors.isEmpty()){
			mv.addObject("okMessage", "THE_PROCESS_FINISHED_SUCCESSFULLY");
		}else{
			mv.addObject("errors",errors);
		}
		
		reasonManager.save(reason);
		mv.addObject("screen", "reasonList.html");
		
		return mv;
	}
}
